package com.bdqn.controller;

import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import com.bdqn.util.FileUploadUtil;
import com.bdqn.util.TokenUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    TokenUtil tokenUtil;
    @Autowired
    FileUploadUtil fileUploadUtil;
    @PostMapping("checkLogin")
    public String checkLogin(@RequestBody Map<String,String> map){
        String token = null;
        //获取用户名和密码
        String uname=map.get("username");
        String pwd=map.get("password");
        //调用service,根据用户名和密码获取用户
        User user=userService.getUser(uname,pwd);
        if (user!=null){
            //登录成功，生成token字符串
            token = tokenUtil.createToken(user);
        }
        return token;
    }

    /**
     * 根据用户编号获取用户对象
     * 从请求头获取token
     */
    @GetMapping("/getUser")
    public User getUser(@RequestHeader("token")String token){
        //解析token，获取用户编号
        int uid = tokenUtil.getUid(token);
        User user=userService.getUser(uid);
        return user;
    }
    @GetMapping("/getUsers")
    public PageInfo<User> User(int pageNum,int pageSize,String uname){
        PageInfo<User> pageInfo=userService.selectPage(pageNum,pageSize,uname);
        return pageInfo;
    }

    @PostMapping("/addUser")
    public int addUser(@RequestBody User user){
        int row = userService.addUser(user);
        return row;
    }
    @GetMapping("selectIdUser")
    public User selectIdUser(int uid){
        User userList = userService.getUser(uid);
        return userList;
    }
    @PostMapping("updateUser")
    public int updateUser(@RequestBody User user){
        int row = userService.updateUser(user);
        return row;
    }
    @GetMapping("deleteUser")
    public int deleteUser(int uid){
        int row = userService.deleteUser(uid);
        return row;
    }
    /**
     * 添加用户的角色
     */
    @GetMapping("addUserRole")
    public int addUserRole(int uid,
                           @RequestParam("rids")List<Integer> rids){
        int row=userService.addUserRole(uid,rids);
        return row;
    }
    @GetMapping("modifyStateClose")
    public int modifyStateClose(int uid){
        int row = userService.modifyStateClose(uid);
        return row;
    }
    @GetMapping("modifyStateOpen")
    public int modifyStateOpen(int uid){
        int row = userService.modifyStateOpen(uid);
        return row;
    }
}
